<template>
  <div>
    <!-- 图标面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 添加按钮 -->
      <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
      <!-- 角色列表数据 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开项-->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['vcenter', 'border-bottom', i1 === 0 ? 'border-top' : '']"
                    v-for="(item1, i1) in scope.row.children" :key="item1.id">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item1.id)">
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二，三级权限 -->
              <el-col :span="19">
                <el-row :class="['vcenter', i2 === 0 ? '' : 'border-top']"
                        v-for="(item2, i2) in item1.children" :key="item2.id">
                    <el-col :span="6">
                      <el-tag type="success"
                              closable @close="removeRightById(scope.row, item2.id)">
                              {{ item2.authName }}
                      </el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <el-col :span="18">
                      <el-tag type="warning" v-for="item3 in item2.children" :key="item3.id"
                              closable @close="removeRightById(scope.row, item3.id)">
                        {{ item3.authName }}
                      </el-tag>
                    </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引项 -->
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeRole(scope.row.id)">删除</el-button>
            <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加对话框 -->
    <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="50%" @close="addDialogClose">
      <!-- 内容主体 -->
      <el-form ref="addRef" :model="addForm" :rules="addRules" label-width="70px" class="add-form">
          <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="addForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
              <el-input v-model="addForm.roleDesc"></el-input>
          </el-form-item>
      </el-form>
       <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改对话框 -->
    <el-dialog title="修改角色" :visible.sync="editDialogVisible" width="50%" @close="editDialogClose">
      <!-- 内容主体 -->
      <el-form ref="editRef" :model="editForm" :rules="editRules" label-width="70px" class="editform">
          <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="editForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
              <el-input v-model="editForm.roleDesc"></el-input>
          </el-form-item>
      </el-form>
       <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%" @close="setRightDialogClose">
      <!-- 内容主体 -->
      <el-tree :data="rightsList" :props="{children:'children', label:'authName'}"
               show-checkbox node-key="id" default-expand-all
               :default-checked-keys="defCheckKeys" ref="treeRef">
      </el-tree>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      rolesList: [], // 所有角色列表数据
      rightsList: [], // 所有权限列表数据
      defCheckKeys: [], // 分配权限选中角色对应存在的权限

      addDialogVisible: false, // 是否显示添加对话框
      editDialogVisible: false, // 是否显示编辑对话框
      setRightDialogVisible: false, // 是否显示分配权限对话框
      addForm: {}, // 添加权限操作对象
      editForm: {}, // 编辑权限操作对象
      setRightForm: {}, // 分配权限操作对象
      // 添加表单的验证规则对象
      addRules: {
        username: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 6, max: 100, message: '长度在 6 到 100 个字符', trigger: 'blur' }
        ]
      },
      // 编辑表单的验证规则对象
      editRules: {
        username: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 6, max: 100, message: '长度在 6 到 100 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    async getRolesList () {
      // 获取角色信息列表
      const { data: res } = await this.$http.get('roles')
        .catch(err => ({ data: { status: 500, message: err } }))
      console.log(res)
      if (res.status !== 200) return this.$message.error('获取角色列表失败！')
      this.$message.success('获取角色列表成功！')
      this.rolesList = res.data
    },
    addDialogClose () {
      // 添加话框的关闭后清空表单
      this.$refs.addRef.resetFields()
    },
    addRole () {
      this.$refs.addRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addForm)
          .catch(err => ({ data: { status: 500, message: err } }))
        console.log(res)
        if (res.status !== 200) return this.$message.error('添加角色失败')
        this.$message.success('添加角色成功')
        // 隐藏添加用户对话框
        this.addDialogVisible = false
        // 重新获取用户列表数据
        this.getRolesList()
      })
    },
    showEditDialog (info) {
      // 打开修改对话框
      this.editDialogVisible = true
      this.editForm = info
    },
    editDialogClose () {
      // 编辑对话框的关闭后清空表单
      this.$refs.editRef.resetFields()
    },
    editRole () {
      // 编辑确定按钮
      this.$refs.editRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('roles', this.editForm)
          .catch(err => ({ data: { status: 500, message: err } }))
        console.log(res)
        if (res.status !== 200) return this.$message.error('修改角色信息失败')
        this.$message.success('修改角色信息成功')
        // 隐藏添加用户对话框
        this.editDialogVisible = false
        // 重新获取用户列表数据
        this.getRolesList()
      })
    },
    async removeRole (id) {
      // 删除按钮
      const confirmResult = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .catch(err => err)

      // 这里需要注意
      // 如果用户点击确定，返回值为字符串 confirm
      // 如果用户点击取消，返回值为字符串 cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      const { data: res } = await this.$http.delete('roles/' + id)
        .catch(err => ({ data: { status: 500, message: err } }))
      console.log(res)
      if (res.status !== 200) return this.$message.error('删除失败!')
      this.$message.success('删除成功!')
      this.getRolesList()
    },
    async removeRightById (row, rightId) {
      // 删除权限
      const confirmResult = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .catch(err => err)

      // 这里需要注意
      // 如果用户点击确定，返回值为字符串 confirm
      // 如果用户点击取消，返回值为字符串 cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      // 该接口会返回该角色下最新的权限数据
      const { data: res } = await this.$http.delete(`roles/${row.id}/rights/${rightId}`)
        .catch(err => ({ data: { status: 500, message: err } }))
      console.log(res)
      if (res.status !== 200) return this.$message.error('删除失败!')
      this.$message.success('删除成功!')
      // 重新获取数据会导致el-table组件的重新渲染, 权限的打开状态也会取消
      // this.getRolesList()
      row.children = res.data
    },
    async showSetRightDialog (role) {
      // 分配权限按钮
      const { data: res } = await this.$http.get('rights/tree')
        .catch(err => ({ data: { status: 500, message: err } }))
      console.log(res)
      if (res.status !== 200) return this.$message.error('获取所有权限的树形数据失败!')
      this.$message.success('获取所有权限的树形数据成功!')
      this.rightsList = res.data
      // 递归获取默认选中的节点Id数组
      // 直接传入对应的数据引用会使得代码更精简
      // 这里要求角色数据必须带有children属性，不然会注入角色id
      this.getLeafKeys(role, this.defCheckKeys)
      this.setRightForm = role
      this.setRightDialogVisible = true
    },
    getLeafKeys (node, arr) {
      // arr 传入数组的引用
      if (!node) return
      if (!node.children) return arr.push(node.id)

      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    setRightDialogClose () {
      // 关闭分配权限对话框时清除默认选中key, 防止再次打开的时候多次添加导致数据错误
      this.defCheckKeys = []
    },
    async allotRights () {
      // 点击为角色分配权限
      const keys = [
        // 选中节点的key
        ...this.$refs.treeRef.getCheckedKeys(),
        // 半选中节点的key
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]

      const { data: res } = await this.$http.post(
        `roles/${this.setRightForm.id}/righsts`,
        { rids: keys.join(',') }
      ).catch(err => ({ data: { status: 500, message: err } }))
      console.log(res)
      if (res.status !== 200) return this.$message.error('分配权限失败!')
      this.$message.success('分配权限成功!')
      this.getRolesList()
      this.setRightDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-table{
  margin-top: 15px;
  font-size: 12px;
}

.el-tag{
  margin:  7px;
}

.border-top{
  border-top: 1px solid #eee;
}

.border-bottom{
  border-bottom: 1px solid #eee;
}

.vcenter{
  display: flex;
  align-items: center;
}
</style>
